package com.example.demo.service;

import com.example.demo.domain.CourseInfo;
import com.example.demo.domain.Student;
import com.example.demo.repository.StudentRepository;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 学生服务类
 */
@Service
public class StudentService {
    //对成员变量、方法和构造函数进行标注，来完成自动装配的工作
    //@Autowired将java对象交给容器管理，由容器自己生成对象、销毁对象
    @Autowired
    private StudentRepository studentRepository;


    /**
     * 查询所有学生信息
     * @return
     */
    public List<Student> findAll(){
        return studentRepository.findAll();
    }

    /**
     * 按学号查询学生信息
     * @param id，整型
     * @return
     */
    public Student findById(String id){
        return studentRepository.findBySid(id);//.orElse(null)作用：如果找到了就返回找到的结果，否则返回null
    }

    /**
     * 根据学生姓名查找学生信息
     * @param name
     * @return
     */
    public List<Student> findByStudentNameLike(String name){
        List<Student> objects = studentRepository.findByStudentNameLike(name);
        System.out.println(objects.size());
        for (int i = 0; i < objects.size(); i++) {
            System.out.println(objects.get(i));
        }
        return studentRepository.findByStudentNameLike(name);
    }

    /**
     * 按学号查询学生选课信息
     * @param id  整型
     * @return
     */
    public List<CourseInfo> findCourseSelectionById(String id){
        List<Map<String,Object>> objects = studentRepository.findCourseSelectionById(id);
        List<CourseInfo> courses = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            CourseInfo course = new CourseInfo();
            for (Map.Entry<String, Object> entry : objects.get(i).entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if(Objects.equals(key, "cid")){
                    course.setCid((String) value);
                }
                if(Objects.equals(key, "sid")){
                    course.setSid((String) value);
                }
                if(Objects.equals(key, "course")){
                    course.setCourse((String) value);
                }
            }
            courses.add(course);
        }
        return courses;
    }
}
